package com.tanhua.app.controllerservice;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.VisitorsApi;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.UserHolder;
import com.tanhua.domain.vo.VisitorsVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private VisitorsApi visitorsApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private RecommendUserApi recommendUserApi;

    public ResponseEntity visitors() {

        // 查询redis获取当前用户的登录时间（首页）
        String time = stringRedisTemplate.opsForValue().get("visitors_user_" + UserHolder.getUser().getId());
        // 查到了---拿着时间去历史访客表中做时间的对比 获取到访客的id

       List<VisitorsVo> voList=new ArrayList();
        if(time!=null){
            List<Visitors> list=visitorsApi.findvisitorsList(Long.parseLong(time),UserHolder.getUser().getId());
            // 根据访客的id获取访客信息
            if(CollectionUtil.isNotEmpty(list)){
                for (Visitors visitors : list) {
                    UserInfo userInfo = userInfoApi.findUserInfo(visitors.getVisitorUserId());

                    // 封装vo返回
                    VisitorsVo vo = new VisitorsVo();
                    vo.setUserInfo(userInfo);
                    //查询当前登录用户和访客之间的缘分值 recommend_user
                    RecommendUser recommendUser = recommendUserApi.findScore(UserHolder.getUser().getId().intValue(), visitors.getVisitorUserId());
                    if(recommendUser==null){
                        recommendUser=new RecommendUser();
                        recommendUser.setScore(99.99);
                    }
                    vo.setFateValue(recommendUser.getScore().longValue());
                    voList.add(vo);
                }
            }

        }

        // 将当前时间作为登录用户最新登录时间 覆盖redis  key:当前登录用户  value:当前时间
        stringRedisTemplate.opsForValue().set("visitors_user_"+ UserHolder.getUser().getId(),System.currentTimeMillis()+"");


        return ResponseEntity.ok(voList);

    }
}
